package com.ruoyi.common.utils;


import com.ruoyi.common.exception.ServiceException;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 此处使用AES-128-ECB加密模式，key需要为16位
 */

public class AESUtil {

    private final static String S_KEY = "zhang.fubojincui";


    public static void main(String[] args) {
        try {
            String decrypt = decrypt("/4RgEPE201HrfNLgpY39uA==");
            String encrypt = encrypt("18883423325");
            System.out.println(String.format("解密后的手机号码：%s",decrypt));
            System.out.println(String.format("加密后手的机号码：%s",encrypt));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密
     *
     * @param sSrc 需要加密的文本
     * @return 加密后的信息
     * @throws Exception 异常信息
     */
    @SneakyThrows
    public static String encrypt(String sSrc){
        checkLength(S_KEY);
        byte[] raw = S_KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));

        return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    /**
     * 解密
     *
     * @param sSrc 需要解密的文本
     * @return 解密后的信息
     */
    public static String decrypt(String sSrc) {
        try {
            checkLength(S_KEY);
            byte[] raw = S_KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, StandardCharsets.UTF_8);
                return originalString;
            } catch (Exception e) {
                throw new ServiceException("解密失败：" + e.getMessage());
            }
        } catch (Exception ex) {
            throw new ServiceException("解密失败：" + ex);
        }
    }


    private static void checkLength(String key) {
        // 判断Key是否为16位
        if (key.length() != 16) {
            throw new ServiceException("Key长度不是16位");
        }
    }

}
